package javacvtest.sqladminserver.Controller;

import javacvtest.sqladminserver.UserRepository;
import javacvtest.sqladminserver.util.JwtProperties;
import javacvtest.sqladminserver.VO.UserVO;
import javacvtest.sqladminserver.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static javacvtest.sqladminserver.util.JwtUtil.createJWT;

// UserController.java
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserRepository userRepository; // 注入 UserRepository

    @PostMapping("login")
    public UserVO  login(@RequestParam String username, @RequestParam String password) {


        log.info("username: {}, password: {}", username, password);

        // 从数据库中获取用户信息
        User user = userRepository.findByUsername(username);
        log.info("user: {}", user);

        if (user == null || !user.getPassword().equals(password)) {
//            throw new RuntimeException("用户名或密码错误");

            return null;
        }

        Map<String, Object> claims = new HashMap<>();

        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        claims.put("role", user.getRole());

        String token= (createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims));

        UserVO userVO  = UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .password(user.getPassword())
                .role(user.getRole())
                .token(token)
                .build();

        return userVO;

    }
}